package com.xxx.demo.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.demo.entity.CustomerEntity;
import com.xxx.demo.entity.TUsers;
import com.xxx.demo.service.CustomerService;
import com.xxx.demo.vo.CustomerPageVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class CustomerController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private CustomerService customerService;
    /**
     * 用户登录，判断用户是否存在
     * @param customerName
     * @param customerPwd
     * @param veryCode
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/customerLogin")
    public String login(String customerName, String customerPwd, String veryCode, HttpSession session, Model model, HttpServletRequest req){
        LineCaptcha lineCaptcha= (LineCaptcha) session.getAttribute("lineCaptcha");
        boolean feiFa=lineCaptcha.verify(veryCode);
        if (!feiFa){ //验证码不正确
            model.addAttribute("msg2","验证码错误");
            return "login";
        }

        CustomerEntity customer=customerService.findByCustomerNameAndPwd(customerName,customerPwd);
        if(customer!=null){
            //使用session
            session.setAttribute("customer",customer);
            req.setAttribute("customer",customer);
            return "redirect:/selectSomeShow";//重定向
        }else {
            model.addAttribute("msg","用户名或者密码错误，请重新输入");
            return "login";
        }
    }

    /**
     * 通过用户账号查询用户
     * @param customerName
     * @return
     */
    @ResponseBody
    @RequestMapping("/queryCustomerByUserName")
    public String queryCustomerByUserName(String customerName){
        Integer flag = customerService.queryCustomerByUserName(customerName);
        if (flag == 0){
            return "0";
        }
        return "1";
    }

    /**
     * 根据用户id查找用户
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/findByCustomerId")
    public String findByCustomerId(Long id, Model model,HttpSession session){
        System.out.println(id);
        CustomerEntity customerEntity =customerService.findByCustomerId(id);
        model.addAttribute("customer",customerEntity);
        TUsers admin1= (TUsers) session.getAttribute("user");
        model.addAttribute("adminSession",admin1);
        return "updateCustomer";
    }

    /**
     * 修改用户
     * @param customer
     * @return
     */
    @RequestMapping("/updateByCustomerId")
    @ResponseBody
    public String updateByCustomerId(@ModelAttribute CustomerEntity customer){
        customerService.updateByCustomerId(customer);
        return "1";
    }

    /**
     * 注册用户
     * @param customer
     * @return
     */
    @RequestMapping("/registerCustomer")
    @ResponseBody
    public String registerCustomer(CustomerEntity customer){
        customerService.registerCustomer(customer);
        return "1";
    }

    /**
     * 分页查询所有用户
     * @param customer
     * @param pageNo
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("/selectCustomerPage")
    public String selectCustomerPage(@ModelAttribute("customer") CustomerEntity customer, Integer pageNo, Integer pageSize, Model model, HttpSession session){
        if (pageNo==null || pageNo<1){
            pageNo=1;
        }
        if (pageSize==null || pageSize<1){
            pageSize=3;
        }
        IPage<CustomerEntity> customerIPage=customerService.selectCustomerPage(pageNo,pageSize,customer);
        List<CustomerEntity> customerEntities =  customerIPage.getRecords();
        List<CustomerPageVo> customerPageVos = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(customerEntities)){
            for (CustomerEntity cus:customerEntities){
                CustomerPageVo customerPageVo = new CustomerPageVo();
                System.out.println(cus.getId().toString());
                customerPageVo.setStrId(cus.getId().toString() + "!");
                System.out.println(customerPageVo.getStrId());

                BeanUtil.copyProperties(cus,customerPageVo);
                Date creationDate = cus.getCreationDate();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = dateFormat.format(creationDate);
                customerPageVo.setRegisterTime(format);
                customerPageVos.add(customerPageVo);
            }
        }
        IPage<CustomerPageVo> customerPageVoIPage = new Page<>();
        BeanUtil.copyProperties(customerIPage,customerPageVoIPage);
        customerPageVoIPage.setRecords(customerPageVos);
        //customerPageVoIPage.setTotal(customerIPage.getTotal());
        //customerPageVoIPage.setCurrent(customerIPage.getCurrent());
        //customerPageVoIPage.setPages(customerIPage.getPages());
        //customerPageVoIPage.setSize(customerIPage.getSize());
        LOGGER.info("分页查询出参：{}" + customerPageVoIPage.getRecords().toString());
        TUsers admin1= (TUsers) session.getAttribute("user");
        model.addAttribute("adminSession",admin1);
        model.addAttribute("customerIPage",customerPageVoIPage);
        return "customerManage";
    }

    /**
     * 根据id删除（假）
     * @param id
     */
    @RequestMapping("/deleteByCustomer")
    @ResponseBody
    public String deleteByCustomer(String id){
        id = id.replace("!","");
        System.out.println(id);
        Long aLong = Long.valueOf(id);
        System.out.println(aLong);
        Integer flag = customerService.deleteByCustomer(aLong);
        if (flag == 0){
            return "0";
        }
        return "1";
    }

    //===================================================用户界面=======================================
    /**
     * 根据用户id查找用户
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/selectByCustomerId")
    public String selectByCustomerId(Long id, Model model,HttpSession session){
        System.out.println(id);
        CustomerEntity byCustomerId = customerService.findByCustomerId(id);
        CustomerPageVo customerPageVo = new CustomerPageVo();
        BeanUtil.copyProperties(byCustomerId,customerPageVo);
        Date creationDate = customerPageVo.getCreationDate();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = dateFormat.format(creationDate);
        customerPageVo.setRegisterTime(format);
        model.addAttribute("customerSession",session.getAttribute("customer"));
        model.addAttribute("customer",customerPageVo);
        return "customerInformation";
    }

    /**
     * 根据用户id查找用户
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/selectByCustomerId2")
    public String selectByCustomerId2(Long id, Model model, HttpSession session){
        System.out.println(id);
        CustomerEntity customerEntity =customerService.findByCustomerId(id);
        model.addAttribute("customerSession",session.getAttribute("customer"));
        model.addAttribute("customer2",customerEntity);
        return "customerInformation";
    }

    /**
     * 修改
     * @param customerEntity
     * @return
     */
    @RequestMapping("/updateCustomer")
    @ResponseBody
    public String updateCustomer(CustomerEntity customerEntity){
        Integer integer = customerService.updateByCustomerId(customerEntity);
        if (integer == 0){
            return "0";
        }else {
            return "1";
        }

    }
}
